<template>
	<view style="padding-bottom: 150rpx;" class="wrapper bg-linear">
		<view class="wrapper shadow1 border-r-10 bg-color m-b-8 p-8">
			<ppl-textarea placeholder="请输入您的详细需求" @onChange="onChangeNeed">
				<view slot="title" class="t-14">填写信息</view>
			</ppl-textarea>

			<!-- 优化：只保留ppl-upload组件，移除手动添加的预览区域 -->
			<ppl-upload :initial-files="initialFiles" @file-change="handleFileChange" @delete-file="handleDeleteFile"
				:max-count="4" />

			<ppl-infoField :use-custom="true">
				<view>
					<!-- 修改为手动输入的取货地址 -->
					<van-field v-model="address" :required="true" placeholder="请输入取货地址" error-message-align="right"
						:error-message="errors.address" input-align="right" @change="validateAddress('address')">
						<view slot="label" class="color8">
							取货地址
						</view>
					</van-field>

					<!-- 修改为手动输入的收货地址 -->
					<van-field v-model="deliveryAddress" :required="true" placeholder="请输入收货地址"
						error-message-align="right" :error-message="errors.deliveryAddress" input-align="right"
						@change="validateAddress('deliveryAddress')">
						<view slot="label" class="color8">
							收货地址
						</view>
					</van-field>

					<van-field :value="bonus" :required="true" placeholder="输入金额" error-message-align="right"
						:error-message="errors.bonus" input-align="right" @change="onChangeBonus">
						<view slot="label" class="color8">
							金额
						</view>
					</van-field>
				</view>
			</ppl-infoField>
		</view>
		<ppl-tips :tips="tips" />
		<ppl-pay @submit="submit" :price="price" />
		<ppl-kd :show="showSelectors" @close="close" @onSelected="onSelected" position="bottom" />
		<van-popup :show="show" @close="show = false" position="bottom">
			<van-picker :show-toolbar="true" :columns="columns" @change="onChangeTime" @confirm="confirmTime" />
		</van-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		watch
	} from 'vue'
	import {
		getGoodsSize,
		postNeed
	} from '@/api/index.js'
	import {
		DELIVERYTIME,
		GENDER
	} from '@/package/constants/index.js'
	import {
		getList,
		payFlag
	} from '@/utils/index.js'
	import {
		addCampusOrder
	} from '@/package/api/insertList.js'
	import {
		getPaymentInfoTo
	} from '@/api/index.js'

	import {
		updateCampusOrder,
		deleteCampusOrder
	} from '@/package/api/update.js'

	// 地址相关响应式数据 - 改为手动输入
	const address = ref(''); // 取货地址
	const deliveryAddress = ref(''); // 收货地址

	// 获取当前用户ID
	const userId = ref(uni.getStorageSync('userId') || '');

	// 初始化所有响应式数据
	const checked = ref(true)
	const bonus = ref('')
	const price = ref(0);
	const cid = ref('');
	const name = ref('');
	const showSelectors = ref(false);
	const show = ref(false)
	const columns = ref([]);
	const currentSelect = ref('');
	const need = ref('');
	const tips = ref(['垃圾可以放门口，拍照通知，谢谢配合', '发布需要实名认证审核通过'])
	const errors = reactive({
		address: '',
		bonus: '',
		deliveryAddress: '' // 新增收货地址错误信息
	});

	// 图片相关响应式数据
	const imgs = ref(''); // 图片信息（逗号分隔的字符串）
	const initialFiles = ref([]); // 图片URL数组，用于预览

	// 生成唯一订单号
	const generateOrderNo = () => {
		const timestamp = new Date().getTime();
		const randomNum = Math.floor(Math.random() * 1000);
		const schoolId = uni.getStorageSync('school_id') || '000';
		return `ORD${schoolId}${timestamp}${randomNum}`;
	}

	// 修改价格计算逻辑，不再依赖大小和currentPrice
	const updatePrice = () => {
		// 基础价格设置为固定值
		const basePrice = 5; // 假设基础价格为5元
		price.value = basePrice + (bonus.value ? Number(bonus.value) : 0);
	}

	const onChangeBonus = (e) => {
		bonus.value = e.detail;
		if (bonus.value) errors.bonus = '';
		updatePrice();
	}

	// 地址输入验证
	const validateAddress = (field) => {
		if (field === 'address' && address.value.trim()) {
			errors.address = '';
		}

		if (field === 'deliveryAddress' && deliveryAddress.value.trim()) {
			errors.deliveryAddress = '';
		}
	}

	const close = () => {
		showSelectors.value = false;
	}

	const onChangeNeed = (e) => {
		need.value = e;
	}

	// 处理文件上传
	const handleFileChange = (fileUrls) => {
		console.log('接收到图片URL列表:', fileUrls);
		initialFiles.value = fileUrls;
		imgs.value = fileUrls.join(',');
		console.log('更新后的图片URL:', imgs.value);
	};

	// 处理图片删除
	const handleDeleteFile = (index) => {
		console.log('删除图片索引:', index);
		if (index >= 0 && index < initialFiles.value.length) {
			const newFiles = [...initialFiles.value];
			newFiles.splice(index, 1);
			initialFiles.value = newFiles;
			imgs.value = newFiles.join(',');
			console.log('删除后的图片URL:', imgs.value);
		}
	};

	const submit = async () => {
		// 验证所有必填字段
		if (!address.value.trim()) {
			errors.address = '请输入取货地址';
			return;
		}
		if (!deliveryAddress.value.trim()) {
			errors.deliveryAddress = '请输入收货地址';
			return;
		}
		if (!bonus.value) {
			errors.bonus = '请输入金额';
			return;
		}

		const amount = Number(bonus.value);
		if (amount < 1) {
			errors.bonus = '支付金额必须大于1元';
			return;
		}
		// 从本地存储中获取查看是否实名
		if (uni.getStorageSync('isrealnameauthenticated') != 1) {
			// 表示未实名
			uni.showToast({
				title: '未进行实名认证,不能发布任务',
				icon: 'none',
				duration: 1000
			});
			return
		}

		try {
			// 构建CampusOrder对象
			const campusOrder = {
				orderNo: generateOrderNo(), // 生成订单号
				orderType: 3, // 外卖代拿
				orderStatus: 0, // 待帮助
				payAmount: price.value.toString(), // 直接传递字符串
				payStatus: 0, // 待支付
				startPlace: address.value.trim(), // 起点为取货地址
				endPlace: deliveryAddress.value.trim(), // 终点为收货地址
				phone: uni.getStorageSync('userPhone') || '', // 从本地获取电话，若无则为空
				imageInfo: imgs.value, // 图片信息（已确保为逗号分隔的字符串）
				pickupInfo: need.value, // 取件信息
				schoolId: uni.getStorageSync('school_id'), // 学校ID
				userId: userId.value // 当前用户ID
			};

			console.log('提交的订单数据:', JSON.stringify(campusOrder));

			// 调用addCampusOrder接口
			const addRes = await addCampusOrder(JSON.stringify(campusOrder));
			console.log('订单添加结果:', addRes);

			if (addRes.data > 0) {
				// 显示支付方式选择
				uni.showActionSheet({
					itemList: ['微信支付', '余额支付'],
					success: function(res) {
						switch (res.tapIndex) {
							case 0: // 微信支付
								handleWechatPay(campusOrder.orderNo, addRes.data);
								break;
							case 1: // 余额支付
								handleBalancePay(campusOrder.orderNo, addRes.data);
								break;
							default:
								console.log('用户取消支付');
						}
					},
					fail: function(err) {
						console.log('显示支付方式选择失败:', err);
					}
				});
			} else {
				uni.showToast({
					title: addRes.msg || '订单添加失败',
					duration: 1000,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('提交订单出错:', e);
			uni.showToast({
				title: '操作失败，请重试',
				duration: 1000,
				icon: 'none'
			});
		}
	}

	// 修改onShow生命周期钩子
	onShow(() => {
		console.log('页面显示，检查用户登录状态');
		// 检查用户是否已登录
		if (!userId.value) {
			userId.value = uni.getStorageSync('userId') || '';
		}
	})

	// 修改onLoad生命周期钩子
	onLoad((options) => {
		console.log('页面加载，初始化数据');
		name.value = options.name || '';
		cid.value = options.cid || '';

		// 初始化用户ID
		if (!userId.value) {
			userId.value = uni.getStorageSync('userId') || '';
		}
	})

	// 余额支付处理函数
	const handleBalancePay = async (orderNo, orderId) => {
		try {
			// 准备余额支付参数
			const yueZhiFuParams = {
				orderNo: orderNo,
				totalAmount: price.value.toFixed(2) // 使用toFixed确保两位小数
			};

			console.log('余额支付参数:', yueZhiFuParams);

			// 显示加载中
			uni.showLoading({
				title: '支付处理中...'
			});

			// 调用余额支付接口（假设接口已移除收货地址相关参数）
			const payRes = await getYueZhiFu(yueZhiFuParams);

			// 隐藏加载
			uni.hideLoading();

			if (payRes.code === 200) {
				// 余额支付成功
				uni.showModal({
					title: '支付结果',
					content: payRes.message || '余额支付成功',
					showCancel: false,
					success: () => {
						// 更新订单状态为已支付
						updateCampusOrder({
							orderNo: orderNo,
							payStatus: 1,
							orderStatus: 1,
							paymentType: 1
						});

						// 重置表单
						resetForm();

						// 跳转首页
						// setTimeout(() => {
						//  uni.switchTab({
						//      url: '/pages/index/index'
						//  });
						// }, 1500);
					}
				});
			} else if (payRes.code === 400) { // 假设后端余额不足返回400错误
				// 余额不足提示
				uni.showToast({
					title: payRes.message || '账户余额不足，请先充值',
					icon: 'none'
				});

				// 删除未支付的订单
				deleteCampusOrder(JSON.stringify({
					id: orderId
				}));
			}
		} catch (error) {
			console.error('余额支付处理异常:', error);
			uni.hideLoading();
			uni.showToast({
				title: '支付处理失败，请重试',
				icon: 'none'
			});
		}
	};

	// 微信支付处理函数（假设接口已移除收货地址相关参数）
	const handleWechatPay = async (items, ido) => {
		try {
			let payData = {
				orderNo: items
			}
			let payres = await getPaymentInfoTo(payData);
			console.log('获取支付信息结果:', payres);

			if (payres.code == 200) {
				wx.requestPayment({
					timeStamp: payres.data.jsConfig.timeStamp,
					nonceStr: payres.data.jsConfig.nonceStr,
					package: payres.data.jsConfig.packageVal,
					paySign: payres.data.jsConfig.paySign,
					signType: payres.data.jsConfig.signType, // 该参数为固定值
					success(res) {
						console.log('支付成功:', res);
						uni.showToast({
							title: '支付成功',
							icon: 'none'
						});

						// 根据订单状态修改订单状态 修改成为已支付
						let data = {
							orderNo: items,
							payStatus: 1,
							orderStatus: 1,
							paymentType: 0
						};

						updateCampusOrder(JSON.stringify(data));

						// 初始化页面数据
						address.value = '';
						deliveryAddress.value = '';
						bonus.value = '';
						need.value = '';
						imgs.value = '';
						initialFiles.value = [];
						price.value = 0;

						// 清除错误提示
						Object.keys(errors).forEach(key => {
							errors[key] = '';
						});
					},
					fail(err) {
						console.error('支付失败:', err);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});

						// 根据订单状态修改订单状态 修改成为已取消
						let data = {
							id: ido
						};

						deleteCampusOrder(JSON.stringify(data));
					}
				});
			}
		} catch (error) {
			console.error('微信支付处理异常:', error);
			uni.showToast({
				title: '支付处理失败，请重试',
				duration: 1000,
				icon: 'none'
			});
		}
	};

	// 重置表单函数
	const resetForm = () => {
		address.value = '';
		deliveryAddress.value = '';
		bonus.value = '';
		need.value = '';
		imgs.value = '';
		initialFiles.value = [];
		price.value = 0;

		Object.keys(errors).forEach(key => {
			errors[key] = '';
		});
	}
</script>

<style scoped>
	/* 调整了.wrapper类的margin-bottom和内边距 */
	::v-deep .van-cell {
		padding-left: 0;
		padding-right: 0;
	}

	::v-deep .van-submit-bar__bar {
		justify-content: space-between;
	}

	::v-deep .van-button--danger {
		background-color: #3c91ff;
		border-radius: 10rpx;
	}

	::v-deep .van-submit-bar__bar {
		box-shadow: -2px -1px 5px 0px rgba(0, 0, 0, 0.05);
	}

	::v-deep .input-placeholder {
		color: #3c91ff !important;
	}

	::v-deep .van-cell--required:before {
		left: -7px;
	}

	::v-deep .van-cell:after {
		right: 0;
		left: 0;
	}

	.express-size-btn {
		width: 70px;
		height: 40px;
		line-height: 40px;
		border-radius: 20rpx;
		border: 1px solid #ddd;
		font-size: 22rpx;
		color: #666;
		white-space: nowrap;
		text-align: center;
		background-color: #fff;
		float: left;
		margin-right: 10px;
	}

	.express-size-btn.active {
		border-color: #3c91ff;
		color: #3c91ff;
		background-color: rgba(60, 145, 255, 0.1);
	}
</style>